
$(function(){
	generatorParamHtml();
	// 全局变量
	var bsDto = null;
	var $pageFrom = $("#pageForm");
	var $configFrom = $("#prodExchConfig");
	var tableName = "MesProdExchConfig";
	var type = $("#type").val();
	var subContextPath = "/mesmoexchconfig";
	var pointAdd = tableName+".Add";
	var preQuery = contextPath +subContextPath +"/";
	var urlById =contextPath+ "/mesprodexchconfig/"+ "getById";
	var urlAddOrEdit = preQuery + "mesMoExchConfigAddOrEdit";
	var urlManage = preQuery + "mesMoExchConfigManage";
	var countEndSnUrl= preQuery + "countEndSn";
	$("#orgId").attr("data-id",cpc);
	
    var phaseCodeInput = $("#phaseCode");
 	var orgInput = $("#orgId");
	var	prodCodeInput = $("#prodCode");
	var tpCodeInput = $("#tpCode");
	var erpMoInput = $("#erpMo");
	
	//图片批量上传
	var savePicture = preQuery + "savePicture";
	var deletePicture = preQuery + "deletePicture";
	var selectPicture = preQuery + "selectPicture";
	
	/*
		if (target.matches('#addButton')) {
		layer.msg('添加按钮被点击！');
		} else if (target.matches('#editButton')) {
	 */
	/*
	//获取包含按钮的容器
	document.getElementById('buttonDivId').addEventListener('click', function(event) {
		let target = event.target;
		if (target.matches('#addButton') || target.matches('#editButton')) {
			debugger;
			let imagePreview =  document.getElementById('image-preview');
			//获取此容器下的所有图片
			let imagesToUpload = imagePreview.querySelectorAll('img');
			let formData = new FormData();
			for (let img of imagesToUpload) {
				//将Data URL转换为 Blob对象
				let blob = dataURLtoBlob(img.src);
				alert('编辑按钮被点击！');
				formData.append('uploadFile', blob);
			}
			formData.append('mtrlCode',document.getElementById('moCode').innerText);
			alert('编辑按钮被点击！');
			fetch(savePicture, {
				method: 'POST',
				body: formData 
			})
			.then(response => response.json())
			.then(data => {
				console.log('成功批量上传：', data.extend.data);
				let pathDisplay = document.getElementById('path-display');
				data.extend.data.forEach(path => {
					let pathItem = document.createElement('p');
					pathItem.appendChild(document.createTextNode('logo地址：'+ path));
					pathDisplay.appendChild(pathItem);
				})
				let logoUrlInput = document.getElementById('logoUrl');
				let currentValue = logoUrlInput.value;
				let newValue = currentValue ? currentValue + ';' + data.extend.data.join(';') : data.extend.data.join(';');
				logoUrlInput.value = newValue;
			})
			.catch(error => {
				console.error('上传失败：', error);
			})
			alert('编辑按钮被点击2！');
		}
	})*/
	
	//页面刷新的操作(批量展示logo图片)
	document.addEventListener('DOMContentLoaded', function() {
		document.getElementById('saveButtonOne').addEventListener('click', function(event) {
			let imagePreview =  document.getElementById('image-preview');
			let files = [];
			//获取此容器下的所有图片
			let images = imagePreview.querySelectorAll('img');
			images.forEach((img) => {
				//确保每个图片都有对应的文件对象
				if (img.file) {
					files.push(img.file);
				}
			})
			let formData = new FormData();
			files.forEach(file => formData.append('uploadFile', file));
			let mnMoCode = document.getElementById('moCode');
			let mnMoCodeOne;
			if (mnMoCode) {
				if (mnMoCode.tagName === 'P') {
					mnMoCodeOne = document.getElementById('moCode').innerText;
				} else if (mnMoCode.tagName === 'INPUT') {
					mnMoCodeOne = document.getElementById('moCode').value;
				} else {
					layer.msg(' 获取到的元素类型既不是 P 也不是 INPUT。。。 ');
					return;
				}
			} else {
				layer.msg(' 获取不到工单编码的元素！  ');
				return;
			}
			if (!mnMoCodeOne || mnMoCodeOne == '') {
				layer.msg(' 请先输入工单编码！！！ ');
				return;
			}
			formData.append('moCode', mnMoCodeOne);
			fetch(savePicture, {
				method: 'POST',
				body: formData 
			})
			.then(response => response.json())
			.then(data => {
				console.log('成功批量上传：', data.extend.data);
				layer.msg(' 上传图片成功！ ');
			})
			.catch(error => {
				console.error('上传失败：', error);
				layer.msg(' 上传图片失败。。。 ');
			})
			//}
		})
			
		let logoUrlInput = document.getElementById('logoUrl');
		let imagePreviewDiv =  document.getElementById('image-preview');
		let pathDisplayDiv = document.getElementById('path-display');
		let urls = logoUrlInput.value.split(';');
		urls.forEach(url => {
			if (url.trim()) {
				//展示图片
				let imgElementOne = document.createElement('img');
				imgElementOne.src = url.trim();
				imgElementOne.style.width = "100";
				imgElementOne.style.float = 'left';
				imgElementOne.style.opacity = '0.5';
				imgElementOne.style.marginRight = '5px';
				//imgElementOne.style.position = 'relative';
				imagePreviewDiv.appendChild(imgElementOne);
				
				//创建删除按钮
				let delBtn = document.createElement('button');
				delBtn.textContent = 'X';
				delBtn.style.marginTop = '0px';
				delBtn.style.marginLeft = '-25px';
				delBtn.style.position = 'absolute';
				delBtn.style.border = 'none';
				delBtn.style.backgroundColor = 'rgb(255, 255, 255)';
				delBtn.style.cursor = 'pointer';
				delBtn.style.float = 'left';
				delBtn.style.border = 'none';
				//设置关联的图片元素
				delBtn.imageElement = imgElementOne.src.split('/').pop();
				delBtn.addEventListener('click', function() {
					imgElementOne.remove();
					this.remove();
					let imageName = this.imageElement;
					let imageNamell = encodeURIComponent(imageName).toString();
					let mnMoCode = document.getElementById('moCode');
					let mnMoCodell
					if (mnMoCode) {
						if (mnMoCode.tagName === 'P') {
							mnMoCodell = document.getElementById('moCode').innerText;
						} else if (mnMoCode.tagName === 'INPUT') {
							mnMoCodell = document.getElementById('moCode').value;
						} else {
							layer.msg(' 获取到的元素类型既不是 P 也不是 INPUT。。。 ');
							return;
						}
					} else {
						layer.msg(' 获取不到工单编码的元素！  ')
						return;
					}
					if (!mnMoCodell || mnMoCodell == '') {
						layer.msg(' 请先输入工单编码！！！ ');
						return;
					}
					let comb = `${imageNamell};${mnMoCodell}`;
					let formDataT = new FormData();
					formDataT.append('deleteFile',comb);
					console.log(imageName);
					fetch(deletePicture, {
						method: 'POST',
						body: formDataT
					})
					.then(response => response.json())
					.then(data => {
						let logoUrlInput = document.getElementById('logoUrl');
						let currentUrls = logoUrlInput.value;
						let urlsArray = currentUrls.split(';');
						let backendUrl = url;
						let filteredUrls = urlsArray.filter(url => url.trim() !== backendUrl.trim());
						let updatedUrls = filteredUrls.join(';');
						logoUrlInput.value = updatedUrls;
						let pathDisplayDivins = document.getElementById('path-display');
						pathDisplayDivins.innerHTML = "";
						let urlss = logoUrlInput.value.split(';');
						urlss.forEach(function(urlo) {
							if (urlo.trim()) {
								let p = document.createElement('p');
								p.textContent = 'logo地址：' + urlo.trim();
								pathDisplayDivins.appendChild(p);
							}
						})
					})
					.catch(error => {
						layer.msg('Error：', error);
					})
				})
				imagePreviewDiv.appendChild(delBtn);
			}
		})
	})
	
    //页面刷新的操作(批量展示logo地址)
	document.addEventListener('DOMContentLoaded', function() {
		let logoUrlInput = document.getElementById('logoUrl');
		let pathDisplayDiv = document.getElementById('path-display');
		let urls = logoUrlInput.value.split(';');
		urls.forEach(function(url) {
			if (url.trim()) {
				var p = document.createElement('p');
				p.textContent = 'logo地址：' + url.trim();
				pathDisplayDiv.appendChild(p);
			}
		})
	});
	
	//查询图片的操作
	document.getElementById('image').addEventListener('change', function(e) {
		let imagePreview = document.getElementById('image-preview');
		let logoUrlInput = document.getElementById('logoUrl');
		//判断不能上传同名文件
		let urls = logoUrlInput.value.split(';');
		let existingFilenames = urls.map(url => {
			return url.trim().split('/').pop();
		})
		let mnMoCode = document.getElementById('moCode');
		console.log('mnMoCode：' + mnMoCode);
		let mnMoCodeOne;
		if (mnMoCode) {
			if (mnMoCode.tagName === 'P') {
				mnMoCodeOne = document.getElementById('moCode').innerText;
				console.log('mnMoCodeOne：' + document.getElementById('moCode').innerText);
			} else if (mnMoCode.tagName === 'INPUT') {
				mnMoCodeOne = document.getElementById('moCode').value;
				console.log('mnMoCodeOne：' + document.getElementById('moCode').value);
			} else {
				layer.msg(' 获取到的元素类型既不是 P 也不是 INPUT。。。 ');
				return;
			}
		} else {
			layer.msg(' 获取不到工单编码的元素！  ')
			return;
		}
		if (!mnMoCodeOne || mnMoCodeOne == '') {
			layer.msg(' 请先输入工单编码！！！ ');
			return;
		}
		let formData = new FormData();
		for (let i = 0; i < e.target.files.length; i++) {
			let file = e.target.files[i];
			let fileName = file.name;
			
			//判断上传的图片大小不能超过1MB
			if (file.size > 1 * 1024 * 1024) {
				layer.msg('文件：' + fileName + ' 太大了，上传的图片不能超过1MB！ ');
				continue;
			}
			
			//判断文件名只能出现字母、数字、下划线
			const validNamePattern = /^[a-zA-Z0-9_ ]+$/;
			let namePart = fileName.split(".").shift();
			if (!validNamePattern.test(namePart)) {
				layer.msg('文件名：' + namePart + ' 包含无效字符，仅允许字母、数字、下划线和空格！ ');
				continue;
			}
			
			if (existingFilenames.includes(fileName)) {
				layer.msg('文件 ' + fileName + ' 已经存在，不能重复上传！ ');
				continue;
			}
			
			let reader = new FileReader();
			reader.onload = (function(theFile) {
				return function(e) {
					let img = document.createElement('img');
					img.src = e.target.result;
					img.alt = theFile.name;
					img.width = "100";
					img.style.float = 'left';
					img.style.opacity= '0.5';
					img.style.marginRight = '5px';
					//设置绝对定位
		  			img.style.position = 'relative';
					//创建删除按钮
					let delBtn = document.createElement('button');
					delBtn.textContent = 'X';
					delBtn.style.marginTop = '0px';
					delBtn.style.marginLeft = '-20px';
					//设置关联的图片元素
					delBtn.imageElement = img;
					delBtn.style.position = 'absolute';
					delBtn.style.border = 'none';
					delBtn.style.backgroundColor = 'rgb(255, 255, 255)';
					delBtn.style.cursor = 'pointer';
					delBtn.style.float = 'left';
					delBtn.style.border= 'none';
					delBtn.addEventListener('click', function() {
						img.remove();
						this.remove();
						let imageName = this.imageElement.alt;
						let imageNamell = encodeURIComponent(imageName).toString();
						let mnMoCode = document.getElementById('moCode');
						let mnMoCodell
						if (mnMoCode) {
							if (mnMoCode.tagName === 'P') {
								mnMoCodell = document.getElementById('moCode').innerText;
							} else if (mnMoCode.tagName === 'INPUT') {
								mnMoCodell = document.getElementById('moCode').value;
							} else {
								layer.msg(' 获取到的元素类型既不是 P 也不是 INPUT。。。 ');
								return;
							}
						} else {
							layer.msg(' 获取不到工单编码的元素！  ')
							return;
						}
						if (!mnMoCodell || mnMoCodell == '') {
							layer.msg(' 请先输入工单编码！！！ ');
							return;
						}
						let comb = `${imageNamell};${mnMoCodell}`;
						let formDataT = new FormData();
						//传入对象
						formDataT.append('deleteFile',comb);
						fetch(deletePicture, {
							method: 'POST',
							body: formDataT
						})
						.then(response => response.json())
						.then(data => {
							let logoUrlInput = document.getElementById('logoUrl');
							let currentUrls = logoUrlInput.value;
							let urlsArray = currentUrls.split(';');
							let backendUrl = data.extend.data[0] || '';
							let filteredUrls = urlsArray.filter(url => url.trim() !== backendUrl.trim());
							let updatedUrls = filteredUrls.join(';');
							logoUrlInput.value = updatedUrls;
							console.log(data.extend.data[0]);
							let pathDisplayDivins = document.getElementById('path-display');
							pathDisplayDivins.innerHTML = "";
							let urlss = logoUrlInput.value.split(';');
							urlss.forEach(function(urlo) {
								if (urlo.trim()) {
									let p = document.createElement('p');
									p.textContent = 'logo地址：' + urlo.trim();
									pathDisplayDivins.appendChild(p);
								}
							})
						})
						.catch(error => {
							layer.msg('Error：', error);
						})
					})
					imagePreview.appendChild(img);
					imagePreview.appendChild(delBtn);
				}
			})(file);
			reader.readAsDataURL(file);
			//使用AJAX上传图片
			formData.append('uploadFile',file);
		}
		formData.append('moCode',mnMoCodeOne);
		fetch(selectPicture, {
				method: 'POST',
				body: formData 
			})
			.then(response => response.json())
			.then(data => {
				console.log('成功批量上传：', data.extend.data);
				let pathDisplay = document.getElementById('path-display');
				data.extend.data.forEach(path => {
					let pathItem = document.createElement('p');
					pathItem.appendChild(document.createTextNode('logo地址：'+ path));
					pathDisplay.appendChild(pathItem);
				})
				let logoUrlInput = document.getElementById('logoUrl');
				let currentValue = logoUrlInput.value;
				let newValue = currentValue ? currentValue + ';' + data.extend.data.join(';') : data.extend.data.join(';');
				logoUrlInput.value = newValue;
			})
			.catch(error => {
				console.error('上传失败：', error);
			})
	});

	//标签添加选中图片
	document.getElementById('image-text').addEventListener('click', function() {
		document.getElementById('image').click();
	});
	
	
    var orgInputAutoBox = orgInput.autoselect({
        onValidateItem:function(success,data,errMsg){
            if(success){
                $(this).attr("data-id",data.companyCode);
                $("#orgName").html(data.messageLocalName)
            }else {
                $("#orgName").html('- -')
            }
        },
    });




   /* var phaseCodeInputAutoBox = phaseCodeInput.autoselect({
        onValidateItem:function(success,data,errMsg){
            if(success){
                $(this).attr("data-id",data.phaseId);
              	$("#phaseId").val(data.phaseId);
            }
        },
        extend:function(){//下拉列表请求参数，注意:该属性要返回下拉请求post数据
            return{
                extPression:{
                    orgId : orgInput.attr("data-id")
                }
            }
        }
    });*/
	
	
	
	 var prodCodeInputAutoBox = prodCodeInput.autoselect({
        onValidateItem:function(success,data,errMsg){
	
			$("#moCode").val("");
            if(success){
                $(this).attr("data-id",data.mtrlId);
              	$("#prodId").val(data.mtrlId);
 				$("#prodName").html(data.phaseName);
				$("#prodDesc").html(data.mtrlDesc);
				$("#prodPackNum").val(data.packQty);
				$("#prodTypeId").val(data.mtypeId);
				$("#phaseId").val(data.phaseId);
				$("#phaseCode").html(data.phaseCode);
				$("#prodTypeCode").html(data.mtypeCode);
				$("#prodMachineName").html(data.prodMachineName);
				$("#prodMachineId").val(data.prodMachineTypeId);
            }else{
				$("#prodName").html('- -');
				$("#prodDesc").html('- -');
				$("#phaseCode").html('- -');
				$("#prodTypeCode").html('- -');
				$("#prodMachineName").html('- -');
			}
        },
        extend:function(){
            return{
                extPression:{
                    orgId : orgInput.attr("data-id"),
					phaseId:phaseCodeInput.attr("data-id")
                }
            }
        }
    }); 



	//工艺路线选择
	
	var tpCodeAutoSelectBox =  tpCodeInput.autoselect({
        onValidateItem:function(success,data,errMsg){
            if(success&&data){
					$("#tpId").val(data.tpId);
					$("#tpName").html(data.tpName);
            }else{
				$("#tpId").val("");
				$("#tpCode").val("");
				$("#tpName").html("--");
			}
        },
        extend:function(){
            return{
                extPression:{
                    orgId : orgInput.attr("data-id"),
					prodId:prodCodeInput.attr("data-id")
                }
            }
        }
    }); 
	tpCodeAutoSelectBox.setDisabled();


var erpMoCodeAutoSelectBox = $('#erpMo').autoselect({
		  onInputValueChange:function(val){
            tpCodeAutoSelectBox.setDisabled();
        },
		onValidateItem:function(success,data,errMsg){
			if(success&&data){
				   tpCodeAutoSelectBox.setDisabled(false);
			}
		},
		 onSelectRow:function(d){//下拉选中事件(非必填)-回调 data 是选择的列表数据组
	        if(!!d){
				var  data  = d[0];
				$("#moId").val(data.moId);
				$("#prodId").val(data.prodId);
				$("#prodCode").html(data.prodCode);
 				$("#prodName").html(data.phaseName);
				$("#prodDesc").html(data.mtrlDesc);
				$("#prodPackNum").val(data.packQty);
				$("#prodTypeId").val(data.mtypeId);
				$("#phaseId").val(data.phaseId);
				$("#phaseCode").html(data.phaseCode);
				$("#prodTypeCode").html(data.mtypeCode);
				$("#prodMachineName").html(data.prodMachineName);
				$("#prodMachineId").val(data.prodMachineTypeId);
				$("#moCode").html(data.moCode);
				//globalVar = $("#moCode").html(data.moCode);
				//console.log(globalVar)
				 prodCodeInput.attr("data-id",data.prodId);
				tpCodeAutoSelectBox.whenOneData();
				//加载产品交互配置数据
				loadProdInfo(data.prodId,1);
			}
	    },
        extend:function(){
            return{
                extPression:{
                    orgId : orgInput.attr("data-id")
                }
            }
        }
	});
	
	//算出产品sn止
	$("#snStart").keydown(function(event){
		if(event.keyCode==13){
			var type=$("#type").val();
			var erpMo=$("#erpMo").val();
			if(type=="edit"){
				erpMo=$("#erpMo").html();
			}
			if(!erpMo){
				layer.msg("请先选择erp工单号");
				$("#erpMo").focus();
				return;
			}
			var prodSnRule=$("#prodSnRule").val();
			if(!prodSnRule){
				layer.msg("请先输入SN格式");
				return false;
			}
			var moId=$("#moId").val();
			if(!moId){
				layer.msg("数据出错，请刷新页面！");
				return false;
			}
			var snStart=$("#snStart").val();
			if(!snStart){
				layer.msg("请先输入产品SN起始值");
				return false;
			}
			
			var postData={
				extend:{erpMo : erpMo , prodSnRule : prodSnRule , moId : moId , snStart:snStart }
			}
			
			RestfulClient.post(countEndSnUrl,postData,function(res){
				if(res.resultCode != resultCode.success){
					AlertVoice.operateFailed(data.resultMsg);
				}else{
					$("#snEnd").val(res.data);
				}
			},function(e){
				AlertVoice.operateFailed(e.exception);
			});
			return false;
		}
	});

	//加载产品交互配置信息
	window.loadProdInfo = function(prodId,type){
			//不是异步
			RestfulClient.options.async = false;
			RestfulClient.post(urlById, {
				"prodId" : prodId
			}, function(data) {
				//globalVar = data.data.moCode;
				//console.log("打印数据：" + data.data.moCode);
				if (data.data != null) {
				   delete data.data.moCode;
				   delete data.data.moId;
				   delete data.data.erpMo;
					if(type==1){
						pageUtils.initForm("pageForm", data.data,"orgName,prodName,prodMachineName,prodTypeCode,prodDesc,prodDesc,phaseCode,prodCode,moCode,tpName,,sopTime1,sopResult1");
						orgInput.attr("data-id",data.data.orgId);
						prodCodeInput.attr("data-id",data.data.prodId);
						tpCodeAutoSelectBox.setDisabled(false);
						if(data.data.sopResultType1=="1"){
							$("#sopPath1").attr("disabled",true);
						}
						var str = $("#ageTime").parent().html();
						if(str.indexOf("<p ")>=0){
							$("#ageTime").text(data.data.ageTime);
						}
					}
					if(data.extend.MesProdExchConfigDtDto){
						var planData=data.extend.MesProdExchConfigDtDto.planData;
						
						if(planData&&planData!="null"){
							$("#mesProdPlanHdIdInit").val(data.extend.MesProdExchConfigDtDto.mesProdPlanHdId);
							$("#isProof").val(data.data.isProof);
							if(data.data.isProof=="2"){//显示防水设备模板
									$("#commonDev").css("display","none");
									$("#waterProofDev").css("display","block");
							}else{
									$("#commonDev").css("display","block");
									$("#waterProofDev").css("display","none");
							}
							var prodPlanCode="";
							//下拉的等于保存的方案
							for(var i=0;i<window.dataList.length;i++){
								if(window.dataList[i].mesProdPlanHdId==data.extend.MesProdExchConfigDtDto.mesProdPlanHdId){
									prodPlanCode=window.dataList[i].prodPlanCode;
								}
							}
							var value=data.extend.MesProdExchConfigDtDto.mesProdPlanHdId;
							data.extend.MesProdExchConfigDtDto.mesProdPlanHdId=value;
							/*var pushItem=JSON.parse(planData);
							window.dataList.push({
								mesProdPlanChildDto:pushItem,
								mesProdPlanHdId:value,
								prodType:data.data.isProof
							});*/
							//$("#selectDrop").append("<option value="+value+">"+prodPlanCode+"(当前)</option>");
							$("#selectDrop").val(value);
							var carType=data.extend.MesProdExchConfigDtDto.carType;
							$("input[name='carType'][value='"+carType+"']").attr("checked",true);
							var dto=JSON.parse(planData);
							initChildForm(dto);
						}
						
					}
					
					//参数配置
					if(data.extend.MesProdExchParamDtDto){
						var paramDto = data.extend.MesProdExchParamDtDto;
						var planData=paramDto.planData;
						if(!!planData){
							$("#mesProdPlanHdIdParam").val(paramDto.mesProdPlanHdId);
							$("#selectDropParam").val(paramDto.mesProdPlanHdId);
							for(var i=0;i<dataExchMoListParam.length;i++){
								if(dataExchMoListParam[i].mesProdPlanHdId==paramDto.mesProdPlanHdId){
									var dto=dataExchMoListParam[i].mesProdPlanChildDto;
									var pData  = dto.paramData;
									//初始为默认模板
									initParamData(pData);
									setTimeout(function(){
										//设置为保存的模板数据
										initParamData(planData);
									},300)
								}
							}
						}	
					}	
					
				}
			},function(e){
				//保存失败提示信息
				$("#erpMo").val("");
				$("#moId").val("");
				AlertVoice.saveFailed(e.exception);
			});
	}
	//工单下拉表
	/**
	var moCodeAutoSelect = $('#moCode').autoselect({
		initForm:function(data){
			$('#moCode').data('selectData',data);
			
		},
		onValidateItem:function(success,data,errMsg){
			moCodeAutoSelect.initForm(data);
			if(success){
				$("#moId").val(data.moId);
				$("#prodId").val(data.prodId);
				$("#prodCode").val(data.prodCode);
 				$("#prodName").html(data.phaseName);
				$("#prodDesc").html(data.mtrlDesc);
				$("#prodPackNum").val(data.packQty);
				$("#prodTypeId").val(data.mtypeId);
				$("#phaseId").val(data.phaseId);
				$("#phaseCode").html(data.phaseCode);
				$("#prodTypeCode").html(data.mtypeCode);
				$("#prodMachineName").html(data.prodMachineName);
				$("#prodMachineId").val(data.prodMachineTypeId);
				 prodCodeInput.attr("data-id",data.prodId);
			}else{
				$('#moCode').data('selectData',null);
			}
		},
        extend:function(){
            return{
                extPression:{
                    orgId : orgInput.attr("data-id")
                }
            }
        }
	}); */
	
	// 表单验证
	 $pageFrom.validate({
		rules : {
			 
				orgId : {
					required : true
				},
				prodCode : {
					required : true
				},
				prodMachineId : {
					required : true
				},
				phaseCode : {
					required : true
				},
				ageTime : {
//					required : true
				},
				progPath : {
//					required : true
				},
				moCode: {
					required : true
				},
				erpMo: {
					required : true
				},
				moId: {
					required : true
				},
				ipcVersion2:{
					require : false
				}
				/*,
				prodIdExt : {
					required : true
				},
				prodSourceSn : {
					required : true
				},
				prodSnRule : {
					required : true
				},
				prodPackNum : {
					required : true
				},
				prodCaseNum : {
					required : true
				},
				ageTime : {
					required : true
				},
				weightMnuit : {
					required : true
				},
				weightMin : {
					required : true
				},
				weightMax : {
					required : true
				},*/
				
			}
		});

	// 初始化表单
	window.preEdit = function() {
		var id = $("#mesProdExchConfigId").val();
		pageUtils.createButton(type, "","B521982173973319680");
		//重新注册粘贴事件
		reloadPaste();
		if (type == "edit" ||type == "view" ) {
			RestfulClient.config({async : false});//同步请求
			RestfulClient.post(urlById, {
				"mesProdExchConfigId" : id
			}, function(data) {
				if (data.data != null) {
					// pageUtils.initForm("pageForm", data.data, "orgId,orgName","prodExchConfigCode");
					if(type == "view"){
						pageUtils.initForm("pageForm", data.data, "orgName,prodName,prodMachineName,prodTypeCode,prodDesc,prodDesc,phaseCode,tpName,erpMo,sopTime1,sopResult1 ","","mesProdExchConfigId,phaseId");
						$("#sysDetailContainer").removeClass("hidden");
					}else{
						pageUtils.initForm("pageForm", data.data,"orgName,prodName,prodMachineName,prodTypeCode,prodDesc,prodDesc,phaseCode,prodCode,tpName,moCode,erpMo,sopTime1,sopResult1");
					}
					$("#wpCode").autoselectInstance().validateItem();
					$("#wpCode2").autoselectInstance().validateItem();
					var str = $("#ageTime").parent().html();
					if(str.indexOf("<p ")>=0){
						$("#ageTime").text(data.data.ageTime);
					}
                    
                    if(data.data.sopResultType1=="1"){
                        $("#sopPath1").attr("disabled",true);
                    }
                    //工单已完工，禁止修改特殊工艺段sop路径
                    if(data.data.moStat=="4"){
                        $("#sopPath1").attr("readonly",true);
                    }

					if(data.data.oldVersion){
						$("input:radio[name='isOldAdaptIpc']").each(function(){
							$(this).attr('disabled',data.data.oldVersion==1);
							$(this).prop('checked', (data.data.oldVersion!=1&&data.data.isOldAdaptIpc==this.value));
						});
					}
					
					
					orgInput.attr("data-id",data.data.orgId);
					prodCodeInput.attr("data-id",data.data.prodId);
					tpCodeAutoSelectBox.setDisabled(false);
					
					if(data.extend.MesProdExchConfigDtDto){
						var planData=data.extend.MesProdExchConfigDtDto.planData;
						
						if(planData&&planData!="null"){
							$("#mesProdPlanHdIdInit").val(data.extend.MesProdExchConfigDtDto.mesProdPlanHdId);
							$("#isProof").val(data.data.isProof);
							if(data.data.isProof=="2"){//显示防水设备模板
									$("#commonDev").css("display","none");
									$("#waterProofDev").css("display","block");
							}else{
									$("#commonDev").css("display","block");
									$("#waterProofDev").css("display","none");
							}
							var prodPlanCode="";
							//下拉的等于保存的方案
							for(var i=0;i<window.dataList.length;i++){
								if(window.dataList[i].mesProdPlanHdId==data.extend.MesProdExchConfigDtDto.mesProdPlanHdId){
									prodPlanCode=window.dataList[i].prodPlanCode;
								}
							}
							var value=data.extend.MesProdExchConfigDtDto.mesProdPlanHdId+"(now)";
							data.extend.MesProdExchConfigDtDto.mesProdPlanHdId=value;
							var pushItem=JSON.parse(planData);
							window.dataList.push({
								mesProdPlanChildDto:pushItem,
								mesProdPlanHdId:value,
								prodType:data.data.isProof
							});
							$("#selectDrop").prepend("<option value="+value+">"+prodPlanCode+"(当前)</option>");
							$("#selectDrop").val(value);
							var carType=data.extend.MesProdExchConfigDtDto.carType;
							$("input[name='carType'][value='"+carType+"']").attr("checked",true);
							var dto=JSON.parse(planData);
							initChildForm(dto);
						}
						
					}else{
						$("#ChatDrop").attr("disabled",true);
						$("#SigNalA").attr("disabled",true);
						$("#SigNalAMax").attr("disabled",true);
			            $("#SigNalAMin").attr("disabled",true);
						$("#VerSionA").attr("disabled",true);
						$("#byteType").attr("disabled",true);
						$("#callStatus").attr("disabled",true);
						
						$("#ChatDrop2").attr("disabled",true);
						$("#SigNalA2").attr("disabled",true);
						$("#SigNalAMax2").attr("disabled",true);
			            $("#SigNalAMin2").attr("disabled",true);
						$("#VerSionA2").attr("disabled",true);
						$("#byteType2").attr("disabled",true);
						$("#callStatus2").attr("disabled",true);
						
						$("#ChatDrop3").attr("disabled",true);
						$("#SigNalA3").attr("disabled",true);
						$("#SigNalAMax3").attr("disabled",true);
			            $("#SigNalAMin3").attr("disabled",true);
						$("#VerSionA3").attr("disabled",true);
						$("#byteType3").attr("disabled",true);
						$("#callStatus3").attr("disabled",true);
						
						$("#DiskMin").attr("disabled",true);
						$("#DiskMax").attr("disabled",true);
						$("#DiskTotal").attr("disabled",true);
						
						$("#SdDiskMin").attr("disabled",true);
						$("#SdDiskMax").attr("disabled",true);
						$("#SdDiskTotal").attr("disabled",true);
						
						$("#SdCardMin").attr("disabled",true);
						$("#SdCardMax").attr("disabled",true);
						$("#SdCardTotal").attr("disabled",true);
						
						$("#UsdOrSdMin").attr("disabled",true);
						$("#UsdOrSdMax").attr("disabled",true);
						$("#UsdOrSdTotal").attr("disabled",true);
						
						$("#UsdMin").attr("disabled",true);
						$("#UsdMax").attr("disabled",true);
						$("#UsdTotal").attr("disabled",true);
						
						$("#ExternalDiskMin").attr("disabled",true);
						$("#ExternalDiskMax").attr("disabled",true);
						$("#ExternalDiskTotal").attr("disabled",true);
					}
					
					//参数配置
					if(data.extend.MesProdExchParamDtDto){
						var paramDto = data.extend.MesProdExchParamDtDto;
						var planData=paramDto.planData;
						if(!!planData){
							$("#mesProdPlanHdIdParam").val(paramDto.mesProdPlanHdId);
							$("#selectDropParam").val(paramDto.mesProdPlanHdId);
							for(var i=0;i<dataExchMoListParam.length;i++){
								if(dataExchMoListParam[i].mesProdPlanHdId==paramDto.mesProdPlanHdId){
									var dto=dataExchMoListParam[i].mesProdPlanChildDto;
									var pData  = dto.paramData;
									//初始为默认模板
									initParamData(pData);
									setTimeout(function(){
										//设置为保存的模板数据
										initParamData(planData);
									},300)
								}
							}
						}	
					}	
					
					
				}
			});
		}else{
			$("#ageTime").val(2);
			$("#ageTime").html(2);
			
			$("#ChatDrop").attr("disabled",true);
			$("#SigNalA").attr("disabled",true);
			$("#SigNalAMax").attr("disabled",true);
            $("#SigNalAMin").attr("disabled",true);
			$("#VerSionA").attr("disabled",true);
			$("#byteType").attr("disabled",true);
			$("#callStatus").attr("disabled",true);
			
			$("#ChatDrop2").attr("disabled",true);
			$("#SigNalA2").attr("disabled",true);
			$("#SigNalAMax2").attr("disabled",true);
            $("#SigNalAMin2").attr("disabled",true);
			$("#VerSionA2").attr("disabled",true);
			$("#byteType2").attr("disabled",true);
			$("#callStatus2").attr("disabled",true);
			
			$("#ChatDrop3").attr("disabled",true);
			$("#SigNalA3").attr("disabled",true);
			$("#SigNalAMax3").attr("disabled",true);
            $("#SigNalAMin3").attr("disabled",true);
			$("#VerSionA3").attr("disabled",true);
			$("#byteType3").attr("disabled",true);
			$("#callStatus3").attr("disabled",true);
			
			$("#DiskMin").attr("disabled",true);
			$("#DiskMax").attr("disabled",true);
			$("#DiskTotal").attr("disabled",true);
			
			$("#SdDiskMin").attr("disabled",true);
			$("#SdDiskMax").attr("disabled",true);
			$("#SdDiskTotal").attr("disabled",true);
			
			$("#SdCardMin").attr("disabled",true);
			$("#SdCardMax").attr("disabled",true);
			$("#SdCardTotal").attr("disabled",true);
			
			$("#UsdOrSdMin").attr("disabled",true);
			$("#UsdOrSdMax").attr("disabled",true);
			$("#UsdOrSdTotal").attr("disabled",true);
			
			$("#UsdMin").attr("disabled",true);
			$("#UsdMax").attr("disabled",true);
			$("#UsdTotal").attr("disabled",true);
			
			$("#ExternalDiskMin").attr("disabled",true);
			$("#ExternalDiskMax").attr("disabled",true);
			$("#ExternalDiskTotal").attr("disabled",true);
		}
	}
	
	$("#ftpPath1,#ftpPath2,#ftpPath3,#ftpPath4,#ftpPath5").on("keyup",function(){
		var value =$(this).val();
		var id = $(this).attr("id");
		var index = id.substr(id.length-1);
		if(!value){
			$("#ftpSoft"+index).val("");
		}else{
			if(value.lastIndexOf("/")>1){
				$("#ftpSoft"+index).val(value.substr(value.lastIndexOf("/")+1));
			}
			if(value.lastIndexOf("\\")>1){
				$("#ftpSoft"+index).val(value.substr(value.lastIndexOf("\\")+1));
			}
		}
			
	})
	
	
	// 编辑按钮事件
	window.toEditForm = function() {
		var id = $("#mesProdExchConfigId").val();
		location.href = urlAddOrEdit + "?id=" + id + "&type=edit";
	}
	// 保存
	window.saveForm = function() {
		if (!$pageFrom.valid()) {return;}
        if($("#sopPath1").val()!=""){
            /*if($("#sopPath1").val().indexOf("SOP")<0){
                AlertVoice.saveFailed("sop路径格式不正确");
                return;
            }*/
        }
        
		var mesProdPlanHdIdInit=$("#mesProdPlanHdIdInit").val();
		if(mesProdPlanHdIdInit){
			mesProdPlanHdIdInit=mesProdPlanHdIdInit.replace("(now)","");
		}
		$("#mesProdPlanHdId").val(mesProdPlanHdIdInit);
		var postData = $pageFrom.serializeObject();
		postData = pageUtils.maergeText($pageFrom, postData);
		var actionType = type;
		if (type == "copy") {actionType = "add";}
		var url = contextPath+ "/mesprodexchconfig/" + actionType;
		
		
		//获取详情数据
//		var configData = $configFrom.serializeObject();
		var configData = getChildData();
		var selectType=$("#selectDrop").val();
		if(selectType&&selectType==0){
			configData=null;
			
		}else if(selectType&&selectType!=0){
			if(configData==null){
				return;
			}
		}
		var prodExchConfigForm = {};
		prodExchConfigForm.mesProdPlanHdId = mesProdPlanHdIdInit;
		prodExchConfigForm.planData = JSON.stringify(configData);
		postData.sopTime1 = "";
        postData.sopResult1 = "";
        
		var prodExchParamForm = {};
		//参数数据收集
		if(!!$("#selectDropParam").val()&&$("#selectDropParam").val()!="0"){
			var mesProdPlanHdIdParam=$("#mesProdPlanHdIdParam").val();
			prodExchParamForm.mesProdPlanHdId = mesProdPlanHdIdParam;
			prodExchParamForm.planData = getParamData();
		}

		if(postData.ageTime=="null"||postData.ageTime==null || !postData.ageTime){
			postData.ageTime = "";
		}

        var data = {
			form : postData,
			extend : {
				prodExchConfigDt : JSON.stringify(prodExchConfigForm),
				carType : $("input[name='carType']:checked").val(),
				prodExchParamForm:JSON.stringify(prodExchParamForm)
			}
		}
		
		//特殊数据校验写在这里
		var flag=checkData(data);
		if(!flag){
			return;
		}
		
		$('[acConfigId]').validateAutoselect(function() {
			AlertVoice.loading("保存中...");
			RestfulClient.options.async = true;
			RestfulClient.post(url, data, function(data) {
				AlertVoice.saveSuccess("", function() {
					location.href = urlManage;
				});
			},function(e){
				//保存失败提示信息
				AlertVoice.saveFailed(e.exception);
			})
		})
	}
	
	function checkData(data){
		var form=data.form;
		if(form.snStart){
			if(!form.snEnd){
				$("#snEnd").showErrorMsg("请输入产品SN止");
				return false;
			}
		}
		return true;
	}
	
	$("#prodSnRule").click(function(){
		tableUtils.removeWarning($("#snStart")); //移除错误消息
		tableUtils.removeWarning($("#snEnd")); //移除错误消息
	});
	$("#snStart").click(function(){
		tableUtils.removeWarning($("#snStart")); //移除错误消息
	});
	$("#snEnd").click(function(){
		tableUtils.removeWarning($("#snEnd")); //移除错误消息
	});
	// 获取子表数据
	function getChildData(){
		var datas={};
		//防水设备只防水模板获取
		if($("#isProof").val()=="2"){
				$("input[name='childItemproof']:checked").each(function(){
					var item=$(this).val();
					datas[item]=1;
				});
				return datas;
		}
		var vercheck=[];
		var flag=true;
		$("input[name='childItem']:checked").each(function(){
			var item=$(this).val();
			if(item=="memoryCheck"){
				datas=dealWithMemory(datas);
				if(datas==null){
					flag=false;
					return false;
				}
			}else if(item=="sub"){
				var subValue=$("#EquiPment").val();
				if(subValue){
					datas.childTypeCheck=subValue;
					datas.childMachineCheck="1";
				}else{
					layer.msg("子机型代码不能为空");
					flag=false;
					return false;
				}
			}else if(item=="gps"){
				datas=dealWithGps(datas);
				if(datas==null){
					flag=false;
					return false;
				}
			}else if(item=="comuniCation"){
				datas.chatType=$("#ChatDrop").val();
				if($("#SigNalA").val() != null || ($("#SigNalAMin").val() != null && $("#SigNalAMax").val() != null)){
                    //datas.chatSignal=$("#SigNalA").val();
                    datas=dealWithChat(datas);
                    if(datas==null){
                        flag=false;
                        return false;
                    }
                }
				datas.chatVersion=$("#VerSionA").val();
				if(!datas.chatSignal&&!datas.chatVersion){
					layer.msg("通信模块数据不能空");
					flag=false;
					return false;
				}else{
					datas.chatCheck="1";
				}
				var byteType=$("#byteType").prop("checked");
				if(byteType){
					datas.byteType="1";
				}
				var callStatus=$("#callStatus").prop("checked");
				if(callStatus){
					datas.callStatus="1";
				}
			}else if(item=="comuniCation2"){
				datas.chatType2=$("#ChatDrop2").val();
				if($("#SigNalA2").val() != null || ($("#SigNalAMin2").val() != null && $("#SigNalAMax2").val() != null)){
                    //datas.chatSignal=$("#SigNalA").val();
                    datas=dealWithChat2(datas);
                    if(datas==null){
                        flag=false;
                        return false;
                    }
                }
				datas.chatVersion2=$("#VerSionA2").val();
				if(!datas.chatSignal2&&!datas.chatVersion2){
					layer.msg("通信模块数据不能空");
					flag=false;
					return false;
				}else{
					datas.chatCheck2="1";
				}
				var byteType2=$("#byteType2").prop("checked");
				if(byteType2){
					datas.byteType2="1";
				}
				var callStatus2=$("#callStatus2").prop("checked");
				if(callStatus2){
					datas.callStatus2="1";
				}
			}else if(item=="comuniCation3"){
				datas.chatType3=$("#ChatDrop3").val();
				if($("#SigNalA3").val() != null || ($("#SigNalAMin3").val() != null && $("#SigNalAMax3").val() != null)){
                    //datas.chatSignal=$("#SigNalA").val();
                    datas=dealWithChat3(datas);
                    if(datas==null){
                        flag=false;
                        return false;
                    }
                }
				datas.chatVersion3=$("#VerSionA3").val();
				if(!datas.chatSignal3&&!datas.chatVersion3){
					layer.msg("通信模块数据不能空");
					flag=false;
					return false;
				}else{
					datas.chatCheck3="1";
				}
				var byteType3=$("#byteType3").prop("checked");
				if(byteType3){
					datas.byteType3="1";
				}
				var callStatus3=$("#callStatus3").prop("checked");
				if(callStatus3){
					datas.callStatus3="1";
				}
			}else if(item=="bluetooth"){
				datas.bluetoothVersion=$("#VerSionB").val();
				datas.bluetoothStatus=$("#blueDrop").val();
				datas.btConnTest=$("#btConnTest").is(":checked")?1:0;
				if(!datas.bluetoothVersion){
					layer.msg("蓝牙模块无数据");
					flag=false;
					return false;
				}else{
					datas.bluetoothCheck="1";
				}
				
				if(datas.bluetoothStatus=="1"){
					datas.bluetoothCnt="N";
					datas.bluetoothCli="N";
					datas.bluetoothClo="N";
					datas.bluetoothMusic="N";
				}else if(datas.bluetoothStatus=="2"){
					datas.bluetoothCnt=$("input[name='bluetoothCnt']:checked").val();
					datas.bluetoothCli=$("input[name='bluetoothCli']:checked").val();
					datas.bluetoothClo=$("input[name='bluetoothClo']:checked").val();
					datas.bluetoothMusic=$("input[name='bluetoothMusic']:checked").val();
				}
			}else if(item=="wifi"){
				datas=dealWithwifi(datas);
				if(datas==null){
					flag=false;
					return false;
				}
			}else if(item=="wiredNetWork"){
				datas.linkNetCheck=1;
				datas.linkNetDefault=$("#linkNetDefault").is(":checked")?1:0;
				var ip=$("#netCheckIp").val();
				if(ip){
					datas.netCheck=ip;
				}else{
					layer.msg("目标ip不能为空");
					flag=false;
					return false;
				}
			}else if(item=="version"){
				vercheck.push(1);
			}else if(item=="mcu"){
				vercheck.push(2);
			}else if(item=="ipc"){
				vercheck.push(3);
			}else if(item=="cardNumber"){
				vercheck.push(4);
			}else if(item=="cp4Version"){
				vercheck.push(5);
			}else if(item=="firmwareVersion"){
				vercheck.push(6);
			}else if(item=="watchVersion"){
				vercheck.push(7);
			}else if(item=="avVersion"){
				vercheck.push(8);
			}else{
				datas[item]=1;
			}
		});
		if(!flag){
			return null;
		}
		if(vercheck.length>0){
			datas.versionCheck=vercheck.join("#");
		}
		return datas;		
	}
	
	function dealWithwifi(datas){
		var signalMin=$("#SigNalBMin").val();
		var signalMax=$("#SigNalBMax").val();
		var signal=$("#SigNalB").val();
		if(signal&&(signalMin||signalMax)){
			layer.msg("wifi数据出错");
			return null;
		}else if(signal){
			if(signal<0||signal>5){
				layer.msg("wifi数据出错");
				return null;
			}
			datas.wifiCheck=signal
		}else if(signalMin&&signalMax){
			if(signalMin>signalMax){
				layer.msg("wifi数据出错");
				return null;
			}
			datas.wifiCheck=signalMin+"#"+signalMax;
		}else{
			layer.msg("WIFI信息无数据");
			return null;
		}
		datas.wifiMode=$("#wifiMode").val();
		datas.wifiMessageCheck="1";
		return datas;
	}
    
    function dealWithChat(datas){
        var signalMin=$("#SigNalAMin").val();
        var signalMax=$("#SigNalAMax").val();
        var signal=$("#SigNalA").val();
        if(signal&&(signalMin||signalMax)){
            layer.msg("通讯模块数据出错");
            return null;
        }else if(signal){
            if(eval(signal)< 0 ||eval(signal)> 5){
                layer.msg("通讯模块数据出错");
                return null;
            }
            datas.chatSignal=signal
        }else if(signalMin&&signalMax){
            if(eval(signalMin) < -100 ||eval(signalMax) > 0){
                layer.msg("通讯模块数据出错");
                return null;
            }
            if(eval(signalMin)> eval(signalMax)){
                layer.msg("通讯模块数据出错");
                return null;
            }
            datas.chatSignal=signalMin+"#"+signalMax;
        }else{
            layer.msg("通讯模块信息无数据");
            return null;
        }
        return datas;
    }

    function dealWithChat2(datas){
        var signalMin2=$("#SigNalAMin2").val();
        var signalMax2=$("#SigNalAMax2").val();
        var signal2=$("#SigNalA2").val();
        if(signal2&&(signalMin2||signalMax2)){
            layer.msg("通讯模块数据出错");
            return null;
        }else if(signal2){
            if(eval(signal2)< 0 ||eval(signal2)> 5){
                layer.msg("通讯模块数据出错");
                return null;
            }
            datas.chatSignal2=signal2
        }else if(signalMin2&&signalMax2){
            if(eval(signalMin2) < -100 ||eval(signalMax2) > 0){
                layer.msg("通讯模块数据出错");
                return null;
            }
            if(eval(signalMin2)> eval(signalMax2)){
                layer.msg("通讯模块数据出错");
                return null;
            }
            datas.chatSignal2=signalMin2+"#"+signalMax2;
        }else{
            layer.msg("通讯模块信息无数据");
            return null;
        }
        return datas;
    }

    function dealWithChat3(datas){
        var signalMin3=$("#SigNalAMin3").val();
        var signalMax3=$("#SigNalAMax3").val();
        var signal3=$("#SigNalA3").val();
        if(signal3&&(signalMin3||signalMax3)){
            layer.msg("通讯模块数据出错");
            return null;
        }else if(signal3){
            if(eval(signal3)< 0 ||eval(signal3)> 5){
                layer.msg("通讯模块数据出错");
                return null;
            }
            datas.chatSignal3=signal3
        }else if(signalMin3&&signalMax3){
            if(eval(signalMin3) < -100 ||eval(signalMax3) > 0){
                layer.msg("通讯模块数据出错");
                return null;
            }
            if(eval(signalMin3)> eval(signalMax3)){
                layer.msg("通讯模块数据出错");
                return null;
            }
            datas.chatSignal3=signalMin3+"#"+signalMax3;
        }else{
            layer.msg("通讯模块信息无数据");
            return null;
        }
        return datas;
    }
	
	function dealWithGps(datas){
		var notdata=0;
		var gpsSum=$("#SateLlite").val();
		if(gpsSum){
				datas.gpsSum=gpsSum;
			}else{
				notdata++;
			}
		datas.gpsModelType=$("#Drop").val();
		datas.gpsVersion=$("#GpsVerSion").val();
		var gpsLongiTude="";
		if($("#LongiTudeMin").val()&&$("#LongiTudeMax").val()){
		var min=Number($("#LongiTudeMin").val());
		var max=Number($("#LongiTudeMax").val());
		if(min>max){
						
			layer.msg("经度数据出错");
			return null;
		}else{
			gpsLongiTude=min+"#"+max;
			datas.gpsLongiTude=gpsLongiTude;
		}
		}else if(!$("#LongiTudeMin").val()&&!$("#LongiTudeMax").val()){
					//不保存
					notdata++;
		}else{
			layer.msg("经度数据出错");
			return null;
		}
		
		var gpsLatiTude="";
		if($("#LatiTudeMin").val()&&$("#LatiTudeMax").val()){
		var min=Number($("#LatiTudeMin").val());
		var max=Number($("#LatiTudeMax").val());
		if(min>max){
						
			layer.msg("经度数据出错");
			return null;
		}else{
			gpsLatiTude=min+"#"+max;
			datas.gpsLatiTude=gpsLatiTude;
		}
		}else if(!$("#LatiTudeMin").val()&&!$("#LatiTudeMax").val()){
					//不保存
					notdata++;
		}else{
			layer.msg("经度数据出错");
			return null;
		}
		if(notdata>0){
			layer.msg("GPS信息数据不全");
			return null;
		}
		datas.gpsCheck="1";
		return datas
	}
	
	//验证存储器容量数据
	function dealWithMemory(datas){
		var flag=false;
		//自带硬盘
		var memoryCheckOne="";
		if($("#DiskMin").val()&&$("#DiskMax").val()){
			var min=Number($("#DiskMin").val());
			var max=Number($("#DiskMax").val());
			if(min<0||max<0||min>max){
				layer.msg("自带硬盘数据出错");
				return null;
			}else{
				memoryCheckOne=min+"#"+max;
				datas.memoryCheckOne=memoryCheckOne;
				flag=true;
			}
		}else if(!$("#DiskMin").val()&&!$("#DiskMax").val()){
			datas.memoryCheckOne=null;
			//不保存
		}else{
			layer.msg("自带硬盘数据出错");
			return null;
		}
		if($("#DiskTotal").val()){
			var total = Number($("#DiskTotal").val());
			/*if($("#DiskMax").val()){
				var max=Number($("#DiskMax").val());
				if(max > total){
					layer.msg("自带硬盘可用空间不可大于总空间");
					return null;
				}
			}*/
			datas.memoryCheckOneTotal=total;
			flag=true;
		}
		
		//自带SD卡/硬盘
		var memoryCheckTwo="";
		if($("#SdDiskMin").val()&&$("#SdDiskMax").val()){
			var min=Number($("#SdDiskMin").val());
			var max=Number($("#SdDiskMax").val());
			if(min<0||max<0||min>max){
				layer.msg("自带SD卡/硬盘数据出错");
				return null;
			}else{
				memoryCheckTwo=min+"#"+max;
				datas.memoryCheckTwo=memoryCheckTwo;
				flag=true;
			}
		}else if(!$("#SdDiskMin").val()&&!$("#SdDiskMax").val()){
			//不保存
			datas.memoryCheckTwo=null;
		}else{
			layer.msg("自带SD卡/硬盘数据出错");
			return null;
		}
		if($("#SdDiskTotal").val()){
			var total = Number($("#SdDiskTotal").val());
			/*if($("#SdDiskMax").val()){
				var max=Number($("#SdDiskMax").val());
				if(max > total){
					layer.msg("自带SD卡/硬盘可用空间不可大于总空间");
					return null;
				}
			}*/
			datas.memoryCheckTwoTotal=total;
			flag=true;
		}

		//SD卡
		var memoryCheckThree="";
		if($("#SdCardMin").val()&&$("#SdCardMax").val()){
			var min=Number($("#SdCardMin").val());
			var max=Number($("#SdCardMax").val());
			if(min<0||max<0||min>max){
				layer.msg("SD卡数据出错");
				return null;
			}else{
				memoryCheckThree=min+"#"+max;
				datas.memoryCheckThree=memoryCheckThree;
				flag=true;
			}
		}else if(!$("#SdCardMin").val()&&!$("#SdCardMax").val()){
			//不保存
			datas.memoryCheckThree=null;
		}else{
			layer.msg("SD卡数据出错");
			return null;
		}
		if($("#SdCardTotal").val()){
			var total = Number($("#SdCardTotal").val());
			/*if($("#SdCardMax").val()){
				var max=Number($("#SdCardMax").val());
				if(max > total){
					layer.msg("SD卡可用空间不可大于总空间");
					return null;
				}
			}*/
			datas.memoryCheckThreeTotal=total;
			flag=true;
		}
		
		//U口/SD卡
		var memoryCheckFour="";
		if($("#UsdOrSdMin").val()&&$("#UsdOrSdMax").val()){
			var min=Number($("#UsdOrSdMin").val());
			var max=Number($("#UsdOrSdMax").val());
			if(min<0||max<0||min>max){
				layer.msg("U口/SD卡数据出错");
				return null;
			}else{
				memoryCheckFour=min+"#"+max;
				datas.memoryCheckFour=memoryCheckFour;
				flag=true;
			}
		}else if(!$("#UsdOrSdMin").val()&&!$("#UsdOrSdMax").val()){
			//不保存
			datas.memoryCheckFour=null;
		}else{
			layer.msg("U口/SD卡数据出错");
			return null;
		}
		if($("#UsdOrSdTotal").val()){
			var total = Number($("#UsdOrSdTotal").val());
			/*if($("#UsdOrSdMax").val()){
				var max=Number($("#UsdOrSdMax").val());
				if(max > total){
					layer.msg("U口/SD卡可用空间不可大于总空间");
					return null;
				}
			}*/
			datas.memoryCheckFourTotal=total;
			flag=true;
		}
		
		//U口
		var memoryCheckFive="";
		if($("#UsdMin").val()&&$("#UsdMax").val()){
			var min=Number($("#UsdMin").val());
			var max=Number($("#UsdMax").val());
			if(min<0||max<0||min>max){
				layer.msg("U口数据出错");
				return null;
			}else{
				memoryCheckFive=min+"#"+max;
				datas.memoryCheckFive=memoryCheckFive;
				flag=true;
			}
		}else if(!$("#UsdMin").val()&&!$("#UsdMax").val()){
			//不保存
			datas.memoryCheckFive=null;
		}else{
			layer.msg("U口数据出错");
			return null;
		}
		if($("#UsdTotal").val()){
			var total = Number($("#UsdTotal").val());
			/*if($("#UsdMax").val()){
				var max=Number($("#UsdMax").val());
				if(max > total){
					layer.msg("U口可用空间不可大于总空间");
					return null;
				}
			}*/
			datas.memoryCheckFiveTotal=total;
			flag=true;
		}
		
		//外置硬盘
		var memoryCheckSix="";
		if($("#ExternalDiskMin").val()&&$("#ExternalDiskMax").val()){
			var min=Number($("#ExternalDiskMin").val());
			var max=Number($("#ExternalDiskMax").val());
			if(min<0||max<0||min>max){
				layer.msg("外置硬盘数据出错");
				return null;
			}else{
				memoryCheckSix=min+"#"+max;
				datas.memoryCheckSix=memoryCheckSix;
				flag=true;
			}
		}else if(!$("#ExternalDiskMin").val()&&!$("#ExternalDiskMax").val()){
			//不保存
			datas.memoryCheckSix=null;
		}else{
			layer.msg("外置硬盘数据出错");
			return null;
		}
		if($("#ExternalDiskTotal").val()){
			var total = Number($("#ExternalDiskTotal").val());
			/*if($("#ExternalDiskMax").val()){
				var max=Number($("#ExternalDiskMax").val());
				if(max > total){
					layer.msg("外置硬盘可用空间不可大于总空间");
					return null;
				}
			}*/
			datas.memoryCheckSixTotal=total;
			flag=true;
		}
		
		if(!flag){
			layer.msg("存储器容量校验无数据");
			return null;
		}
		datas.memoryCheck="1";
		return datas;
	}
	
	
	//初始化子表数据
	function initChildForm(dto){
		if(dto.memoryCheck==1){
			$("#memoryCheck").prop("checked",true);
		}else{
			$("#DiskMin").attr("disabled",true);
			$("#DiskMax").attr("disabled",true);
			$("#DiskTotal").attr("disabled",true);
			
			$("#SdDiskMin").attr("disabled",true);
			$("#SdDiskMax").attr("disabled",true);
			$("#SdDiskTotal").attr("disabled",true);
			
			$("#SdCardMin").attr("disabled",true);
			$("#SdCardMax").attr("disabled",true);
			$("#SdCardTotal").attr("disabled",true);
			
			
			$("#UsdOrSdMin").attr("disabled",true);
			$("#UsdOrSdMax").attr("disabled",true);
			$("#UsdOrSdTotal").attr("disabled",true);
			
			$("#UsdMin").attr("disabled",true);
			$("#UsdMax").attr("disabled",true);
			$("#UsdTotal").attr("disabled",true);
			
			$("#ExternalDiskMin").attr("disabled",true);
			$("#ExternalDiskMax").attr("disabled",true);
			$("#ExternalDiskTotal").attr("disabled",true);
		}
		
		if(dto.childMachineCheck==1){
			$("#sub").prop("checked",true);
		}
		if(dto.byteType==1){
			$("#byteType").prop("checked",true);
		}
		if(dto.gpsCheck==1){
			$("#gps").prop("checked",true);
		}
		if(dto.chatCheck==1){
			$("#comuniCation").prop("checked",true);
		}else{
			$("#ChatDrop").attr("disabled",true);
			$("#SigNalA").attr("disabled",true);
			$("#SigNalAMax").attr("disabled",true);
            $("#SigNalAMin").attr("disabled",true);
			$("#VerSionA").attr("disabled",true);
			$("#byteType").attr("disabled",true);
			$("#callStatus").attr("disabled",true);
		}
		
		if(dto.chatCheck2==1){
			$("#comuniCation2").prop("checked",true);
		}else{
			$("#ChatDrop2").attr("disabled",true);
			$("#SigNalA2").attr("disabled",true);
			$("#SigNalAMax2").attr("disabled",true);
            $("#SigNalAMin2").attr("disabled",true);
			$("#VerSionA2").attr("disabled",true);
			$("#byteType2").attr("disabled",true);
			$("#callStatus2").attr("disabled",true);
		}
		
		if(dto.chatCheck3==1){
			$("#comuniCation3").prop("checked",true);
		}else{
			$("#ChatDrop3").attr("disabled",true);
			$("#SigNalA3").attr("disabled",true);
			$("#SigNalAMax3").attr("disabled",true);
            $("#SigNalAMin3").attr("disabled",true);
			$("#VerSionA3").attr("disabled",true);
			$("#byteType3").attr("disabled",true);
			$("#callStatus3").attr("disabled",true);
		}
		
		if(dto.bluetoothCheck==1){
			$("#bluetooth").prop("checked",true);
		}
		if(dto.wifiMessageCheck==1){
			$("#wifi").prop("checked",true);
		}
		if(dto.linkNetCheck==1){
			$("#wiredNetWork").prop("checked",true);
		}
		if(dto.pressureRead==1){
			$("#pressureRead").prop("checked",true);
		}
		if(dto.leakageRead==1){
			$("#leakageRead").prop("checked",true);
		}
		if(dto.programRead==1){
			$("#programRead").prop("checked",true);
		}
		if(dto.maxMinRead==1){
			$("#maxMinRead").prop("checked",true);
		}
		
		$("#childId").val(dto.mesProdPlanChildId);
		
		//处理存储器容量
		var memoryCheck=false;
		if(dto.memoryCheckOne){
			var oneList=dto.memoryCheckOne.split("#");
			if(oneList.length=2){
				$("#DiskMin").val(oneList[0]);
				$("#DiskMax").val(oneList[1]);
				memoryCheck=true;
			}
		}
		if(dto.memoryCheckOneTotal){
			$("#DiskTotal").val(dto.memoryCheckOneTotal);
			memoryCheck=true;
		}
		
		if(dto.memoryCheckTwo){
			var oneList=dto.memoryCheckTwo.split("#");
			if(oneList.length=2){
				$("#SdDiskMin").val(oneList[0]);
				$("#SdDiskMax").val(oneList[1]);
				memoryCheck=true;
			}
		}
		if(dto.memoryCheckTwoTotal){
			$("#SdDiskTotal").val(dto.memoryCheckTwoTotal);
			memoryCheck=true;
		}
		
		if(dto.memoryCheckThree){
			var oneList=dto.memoryCheckThree.split("#");
			if(oneList.length=2){
				$("#SdCardMin").val(oneList[0]);
				$("#SdCardMax").val(oneList[1]);
				memoryCheck=true;
			}
		}
		if(dto.memoryCheckThreeTotal){
			$("#SdCardTotal").val(dto.memoryCheckThreeTotal);
			memoryCheck=true;
		}
		
		if(dto.memoryCheckFour){
			var oneList=dto.memoryCheckFour.split("#");
			if(oneList.length=2){
				$("#UsdOrSdMin").val(oneList[0]);
				$("#UsdOrSdMax").val(oneList[1]);
				memoryCheck=true;
			}
		}
		if(dto.memoryCheckFourTotal){
			$("#UsdOrSdTotal").val(dto.memoryCheckFourTotal);
			memoryCheck=true;
		}
		
		if(dto.memoryCheckFive){
			var oneList=dto.memoryCheckFive.split("#");
			if(oneList.length=2){
				$("#UsdMin").val(oneList[0]);
				$("#UsdMax").val(oneList[1]);
				memoryCheck=true;
			}
		}
		if(dto.memoryCheckFiveTotal){
			$("#UsdTotal").val(dto.memoryCheckFiveTotal);
			memoryCheck=true;
		}
		
		if(dto.memoryCheckSix){
			var oneList=dto.memoryCheckSix.split("#");
			if(oneList.length=2){
				$("#ExternalDiskMin").val(oneList[0]);
				$("#ExternalDiskMax").val(oneList[1]);
				memoryCheck=true;
			}
		}
		if(dto.memoryCheckSixTotal){
			$("#ExternalDiskTotal").val(dto.memoryCheckSixTotal);
			memoryCheck=true;
		}
		
		if(memoryCheck){$("#memoryCheck").prop("checked",true);}
		//处理设备子机型
		if(dto.childTypeCheck){
			$("#sub").prop("checked",true);
			$("#EquiPment").val(dto.childTypeCheck);
		}
		//处理GPS
		var gpsCheck=false;
		if(dto.gpsSum){
			$("#SateLlite").val(dto.gpsSum);
			gpsCheck=true;
		}
		if(dto.gpsVersion){
			$("#GpsVerSion").val(dto.gpsVersion);
			gpsCheck=true;
		}
		if(dto.gpsModelType){
			$("#Drop").val(dto.gpsModelType);
			gpsCheck=true;
		}
		if(dto.gpsLatiTude){
			var latitudeList=dto.gpsLatiTude.split("#");
			if(latitudeList.length==2){
				$("#LatiTudeMin").val(latitudeList[0]);
				$("#LatiTudeMax").val(latitudeList[1]);
				gpsCheck=true;
			}
			
		}
		if(dto.gpsLongiTude){
			var longiTudeList=dto.gpsLongiTude.split("#");
			if(longiTudeList.length==2){
				$("#LongiTudeMin").val(longiTudeList[0]);
				$("#LongiTudeMax").val(longiTudeList[1]);
				gpsCheck=true;
			}
		}
		if(gpsCheck){$("#gps").prop("checked",true);}
		//处理通讯模块
		var chatCheck=false;
		if(dto.chatType){
			$("#ChatDrop").val(dto.chatType);
			chatCheck=true;
		}
		if(dto.chatSignal){
			var signalList=dto.chatSignal.split("#");
            if(signalList.length==1){
                $("#SigNalA").val(signalList[0]);
            }else if(signalList.length==2){
                $("#SigNalAMin").val(signalList[0]);
                $("#SigNalAMax").val(signalList[1]);
            }
			chatCheck=true;
		}
		if(dto.chatVersion){
			$("#VerSionA").val(dto.chatVersion);
			chatCheck=true;
		}
		if(dto.byteType && dto.byteType == "1"){
			$("#byteType").prop("checked",true);
			chatCheck=true;
		}
		if(dto.callStatus&&dto.callStatus=="1"){
			$("#callStatus").prop("checked",true);;
			chatCheck=true;
		}
		if(chatCheck){
			$("#comuniCation").prop("checked",true);
		}
		
		
		var chatCheck2=false;
		if(dto.chatType2){
			$("#ChatDrop2").val(dto.chatType2);
			chatCheck2=true;
		}
		if(dto.chatSignal2){
			var signalList2=dto.chatSignal2.split("#");
            if(signalList2.length==1){
                $("#SigNalA2").val(signalList2[0]);
            }else if(signalList2.length==2){
                $("#SigNalAMin2").val(signalList2[0]);
                $("#SigNalAMax2").val(signalList2[1]);
            }
			chatCheck2=true;
		}
		if(dto.chatVersion2){
			$("#VerSionA2").val(dto.chatVersion2);
			chatCheck2=true;
		}
		if(dto.byteType2 && dto.byteType2 == "1"){
			$("#byteType2").prop("checked",true);
			chatCheck2=true;
		}
		if(dto.callStatus2&&dto.callStatus2=="1"){
			$("#callStatus2").prop("checked",true);;
			chatCheck2=true;
		}
		if(chatCheck2){
			$("#comuniCation2").prop("checked",true);
		}
		
		
		var chatCheck3=false;
		if(dto.chatType3){
			$("#ChatDrop3").val(dto.chatType3);
			chatCheck3=true;
		}
		if(dto.chatSignal3){
			var signalList3=dto.chatSignal3.split("#");
            if(signalList3.length==1){
                $("#SigNalA3").val(signalList3[0]);
            }else if(signalList3.length==2){
                $("#SigNalAMin3").val(signalList3[0]);
                $("#SigNalAMax3").val(signalList3[1]);
            }
			chatCheck3=true;
		}
		if(dto.chatVersion3){
			$("#VerSionA3").val(dto.chatVersion3);
			chatCheck3=true;
		}
		if(dto.byteType3 && dto.byteType3 == "1"){
			$("#byteType3").prop("checked",true);
			chatCheck3=true;
		}
		if(dto.callStatus3&&dto.callStatus3=="1"){
			$("#callStatus3").prop("checked",true);;
			chatCheck3=true;
		}
		if(chatCheck3){
			$("#comuniCation3").prop("checked",true);
		}
		
		//处理蓝牙模块
		var blueCheck=false;
		if(dto.bluetoothStatus){
			$("#blueDrop").val(dto.bluetoothStatus);
			if(dto.bluetoothStatus=="2"){
				$("#blueSelect").removeClass("hidden");
				$("input[name='bluetoothCnt'][value='"+dto.bluetoothCnt+"']").attr("checked","checked");
				$("input[name='bluetoothCli'][value='"+dto.bluetoothCli+"']").attr("checked","checked");
				$("input[name='bluetoothClo'][value='"+dto.bluetoothClo+"']").attr("checked","checked");
				$("input[name='bluetoothMusic'][value='"+dto.bluetoothMusic+"']").attr("checked","checked");
			}
			blueCheck=true;
		}
		if(dto.bluetoothVersion){
			$("#VerSionB").val(dto.bluetoothVersion);
			blueCheck=true;
		}
		if(dto.btConnTest && dto.btConnTest == "1"){
			$("#btConnTest").prop("checked",true);
			blueCheck=true;
		}
		if(blueCheck){$("#bluetooth").prop("checked",true);}
		//处理有线网络状态
		if(dto.netCheck){
			$("#wiredNetWork").prop("checked",true);
			$("#netCheckIp").val(dto.netCheck);
		}
		if(dto.linkNetDefault && dto.linkNetDefault == "1"){
			$("#wiredNetWork").prop("checked",true);
			$("#linkNetDefault").prop("checked",true);
		}
		//处理wifi
		if(dto.wifiCheck){
			var signalList=dto.wifiCheck.split("#");
			if(signalList.length==1){
				$("#SigNalB").val(signalList[0]);
				$("#wifi").prop("checked",true);
			}else if(signalList.length==2){
				$("#SigNalBMin").val(signalList[0]);
				$("#SigNalBMax").val(signalList[1]);
				$("#wifi").prop("checked",true);
			}
			if(dto.wifiMode){
				$("#wifiMode").val(dto.wifiMode);
			}
		}
		//处理无输入勾选
		$("input[name='childItem']").each(function(){
			var item=$(this).val();
			if(item=="version"||item=="mcu"||item=="ipc"||item=="cardNumber"||item=="cp4Version"||item=="firmwareVersion"||item=="watchVersion"||item=="avVersion"){
				if(dto.versionCheck){
					var list=dto.versionCheck.split("#");
					for(var i=0;i<list.length;i++){
						if(list[i]=="1"){
							$("#version").prop("checked",true);
						}else if(list[i]=="2"){
							$("#mcu").prop("checked",true);
						}else if(list[i]=="3"){
							$("#ipc").prop("checked",true);
						}else if(list[i]=="4"){
							$("#cardNumber").prop("checked",true);
						}else if(list[i]=="5"){
							$("#cp4Version").prop("checked",true);
						}else if(list[i]=="6"){
							$("#firmwareVersion").prop("checked",true);
						}else if(list[i]=="7"){
							$("#watchVersion").prop("checked",true);
						}else if(list[i]=="8"){
							$("#avVersion").prop("checked",true);
						}
					}
				}
			}else if(dto[item]==1){
				$(this).prop("checked",true);
			}
		});
	}
	
	
    
    //工序编码下拉选择
    var wpCodeAutoSelectBox = $("input[name='wpCode']").autoselect({
       extend:function(){
            return{
                extPression: {
                    orgId : $("#orgId").val(),
                        tpCode : $("#tpCode").val()
                }
            }
        },
        onSelectRow:function(data){//下拉选中事件(非必填)-回调 data 是选择的列表数据组
            if(data){
                var data = data[0];
                $("#wpId").val(data.wpId);
                $("#wpName").html(data.wpName);
               
            }else {
                $("#wpId").val("");
                $("#wpName").html("--");
            }
        },
        onInputValueChange:function(){
            if($("#wpCode").val() ==""){
                 $("#wpId").val("");
                $("#wpName").html("--");
            }
        }
    });
    
      //工序编码下拉选择
    var wpCodeAutoSelectBox2 = $("input[name='wpCode2']").autoselect({
       extend:function(){
            return{
                extPression: {
                    orgId : $("#orgId").val(),
                    tpCode : $("#tpCode").val()
                }
            }
        },
        onSelectRow:function(data){//下拉选中事件(非必填)-回调 data 是选择的列表数据组
             if(data){
                var data = data[0];
                $("#wpId2").val(data.wpId);
                $("#wpName2").html(data.wpName);
               
            }else {
                $("#wpId2").val("");
                $("#wpName2").html("--");
            }
        },
        onInputValueChange:function(){
            if($("#wpCode2").val() ==""){
                 $("#wpId2").val("");
                $("#wpName2").html("--");
            }
        }
    });
    
	// 重新注册输入框粘贴事件，并且排除ftppath1和ftppath2两个输入框
	function reloadPaste(){
		$("body").off("paste",null);
		//输入域粘贴文本去除前后空格
		$("body").on("paste", function (e) {
			var el = $(e.target);
			if (el[0].nodeName.toLowerCase() == 'input' || el[0].nodeName.toLowerCase() == 'textarea') {
				if( (el[0].id != 'ftpPath1' && el[0].id != 'ftpPath2' && el[0].id != 'ftpPath3' && el[0].id != 'ftpPath4' && el[0].id != 'ftpPath5')) {
					var paste = (e.clipboardData || window.clipboardData || e.originalEvent.clipboardData || window.originalEvent.clipboardData).getData("text").trim();
					el.val(paste);
					e.preventDefault();
				}
			}
		})
	}
    
    /**
     *  sop预览
     */
    $("#viewSop").on("click",function(){
        var moId=$("#moId").val();
        var newWindow = window.open("about:blank");
        var url = "http://10.21.2.57:28833/ims-mes/sop/openDownExcel?moId=" + moId;
        newWindow.location.href = url;
        
  /*      var downUrl = contextPath+"/sop/openSopExcel";
        var param = {};
        param.moId = $("#moId").val();;
        RestfulClient.post(downUrl,param,function(res){
                if(res.resultCode != resultCode.success){
                    AlertVoice.operateFailed(data.resultMsg);
                }else{
                    $("#snEnd").val(res.data);
                }
            },function(e){
                AlertVoice.operateFailed(e.exception);
            });  */
    });


	$("input:radio[name='oldVersion']").change(function(e){
		var oldVersion = this.value;
		$("input:radio[name='isOldAdaptIpc']").each(function(){
			$(this).attr('disabled',oldVersion==1);
			$(this).prop('checked',(oldVersion!=1&&this.value == 'Y'));
		});
	});

	// 初始化页面
	$(function() {
		// 占位符 错误信息初始化 必填样式==
		pageUtils.initPage({
			formName : "#pageForm",
			type : type,
			loadDefaultOrg : true,
			dateIds : [ {type:"datetime",elem:"#shipDate",showBottom : true} ]
		});
	});

	
}($))